<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>青云教育系统 - 教师端</title>
    <link rel="stylesheet" href="../../teacher.css">
</head>
<body>
    <div class="layout">
        <aside class="sidebar">
            <div class="brand">青云教育 · 教师端</div>
            <nav class="menu" id="menu">
                <button class="menu-item" data-view="profile" data-url="/index">教员信息及考勤</button>
                <button class="menu-item" data-view="schedule" data-url="/schedule">教师课表</button>
                <button class="menu-item active" data-view="password" data-url="/password">修改密码</button>
                <button class="menu-item" data-view="students" data-url="/students">学生信息</button>
                <button class="menu-item" data-view="upload" data-url="/postmaterial">上传资料</button>
                <button class="menu-item" data-view="download" data-url="/download">下载资料</button>
                <button class="menu-item" data-view="mymaterials" data-url="/mymaterials">我的资料</button>
            </nav>
        </aside>
        <main class="content">
            <header class="topbar">
                <div class="left">
                    <h1 id="view-title">修改密码</h1>
                </div>
                <div class="right">
                    <div class="user-info">
                        <img id="user-avatar" class="user-avatar" src="" alt="用户头像">
                        <span id="teacher-name" class="user-name"></span>
                    </div>
                    <button id="logoutBtn" class="btn btn-secondary">退出登录</button>
                </div>
            </header>

            <section id="view-password" class="view" style="display:block;">
                <div class="card">
                    <div class="card-header">修改密码</div>
                    <div class="card-body">
                        <form id="passwordForm" class="form">
                            <div class="form-group"><label>当前密码</label><input type="password" id="oldPassword" required></div>
                            <div class="form-group"><label>新密码</label><input type="password" id="newPassword" required></div>
                            <div class="form-group"><label>确认新密码</label><input type="password" id="confirmPassword" required></div>
                            <button type="submit" class="btn btn-primary">提交修改</button>
                            <div id="passwordMsg" class="message" style="display:none;"></div>
                        </form>
                    </div>
                </div>
            </section>
        </main>
    </div>

    <script src="../../teacher.js"></script>
    <script>
        // 确保退出登录功能正常工作
        document.addEventListener('DOMContentLoaded', function(){
            // 定义消息提示函数（如果teacher.js中的函数不可用）
            function showMsg(el, msg, type='info'){
                if (!el) {
                    console.error('消息元素不存在');
                    return;
                }
                el.textContent = msg;
                el.className = `message ${type}`;
                el.style.display = 'block';
                setTimeout(()=>{ el.style.display='none'; }, 4000);
                console.log('显示消息:', msg, '类型:', type);
            }
            // 确保修改密码表单绑定正确
            const passwordForm = document.getElementById('passwordForm');
            if (passwordForm) {
                console.log('找到修改密码表单，ID:', passwordForm.id);
                
                // 手动绑定表单提交事件，确保不被其他事件覆盖
                passwordForm.addEventListener('submit', function(e) {
                    console.log('修改密码表单提交事件被触发');
                    e.preventDefault();
                    e.stopPropagation();
                    
                    // 调用teacher.js中的修改密码逻辑
                    const oldPassword = document.getElementById('oldPassword')?.value?.trim();
                    const newPassword = document.getElementById('newPassword')?.value?.trim();
                    const confirmPassword = document.getElementById('confirmPassword')?.value?.trim();
                    const msg = document.getElementById('passwordMsg');
                    
                    console.log('表单数据:', { oldPassword, newPassword, confirmPassword });
                    
                                         if(!oldPassword || !newPassword || !confirmPassword){
                         console.log('表单验证失败：请完整填写');
                         showMsg(msg, '请完整填写', 'error'); 
                         return;
                     }
                                         if(newPassword !== confirmPassword){
                         console.log('表单验证失败：两次密码不一致');
                         showMsg(msg, '两次输入的新密码不一致', 'error'); 
                         return;
                     }
                                         // 密码格式验证（与后端保持一致：4-32位）
                     if(newPassword.length < 4 || newPassword.length > 32){
                         console.log('表单验证失败：密码长度不符合要求');
                         showMsg(msg, '新密码长度必须在4-32位之间', 'error'); 
                         return;
                     }
                    
                    // 调用API
                    submitPasswordChange(oldPassword, newPassword, msg, passwordForm);
                });
            } else {
                console.error('未找到修改密码表单！');
            }
            
            // 修改密码API调用函数
            async function submitPasswordChange(oldPassword, newPassword, msg, form) {
                try {
                    const submitBtn = form.querySelector('button[type="submit"]');
                    if (submitBtn) { 
                        submitBtn.disabled = true; 
                        submitBtn.textContent = '提交中...'; 
                    }
                    
                    // 获取用户token
                    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                    const token = userInfo.token;
                    
                    if (!token) {
                        showMsg(msg, '未找到用户token，请重新登录', 'error');
                        return;
                    }
                    
                    console.log('调用修改密码接口:', '/user/updatePassword');

                    // 调用后端接口
                    const response = await fetch('/user/updatePassword', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': token
                        },
                        body: JSON.stringify({ oldPassWord: oldPassword, newPassWord: newPassword })
                    });
                    
                                         if (response.ok) {
                         const res = await response.json();
                         console.log('修改密码接口响应:', res);
                         
                         // 处理后端返回的Result对象
                         if (res && res.success === true) {
                             // 修改成功
                             showMsg(msg, '密码修改成功！', 'success');
                             form.reset();
                             
                             // 可选：显示成功后的操作提示
                             setTimeout(() => {
                                 showMsg(msg, '密码已更新，请使用新密码重新登录', 'info');
                             }, 2000);
                             
                         } else {
                             // 修改失败，显示具体错误信息
                             const errorMessage = res?.errorMsg || '修改失败，请重试';
                             showMsg(msg, errorMessage, 'error');
                             
                             // 根据错误类型给出具体提示
                             if (errorMessage.includes('原密码')) {
                                 showMsg(msg, '原密码输入错误，请检查后重试', 'error');
                             } else if (errorMessage.includes('格式错误')) {
                                 showMsg(msg, '新密码格式不正确，请确保密码长度在4-32位之间', 'error');
                             } else if (errorMessage.includes('未登录')) {
                                 showMsg(msg, '登录已过期，请重新登录', 'error');
                                 // 可选：自动跳转到登录页
                                 setTimeout(() => {
                                     window.location.href = '/login.html';
                                 }, 3000);
                             }
                         }
                     } else {
                         // HTTP状态码错误
                         const errorText = await response.text();
                         console.error('修改密码请求失败:', response.status, errorText);
                         
                         let errorMessage = `网络请求失败 (${response.status})`;
                         if (response.status === 401) {
                             errorMessage = '登录已过期，请重新登录';
                         } else if (response.status === 403) {
                             errorMessage = '权限不足，无法修改密码';
                         } else if (response.status === 500) {
                             errorMessage = '服务器内部错误，请稍后重试';
                         }
                         
                         showMsg(msg, errorMessage, 'error');
                     }
                } catch(err) {
                    console.error('修改密码异常:', err);
                    showMsg(msg, '修改失败：' + (err.message || err), 'error');
                } finally {
                    const submitBtn = form.querySelector('button[type="submit"]');
                    if (submitBtn) { 
                        submitBtn.disabled = false; 
                        submitBtn.textContent = '提交修改'; 
                    }
                }
            }
            // 绑定退出登录按钮事件（如果teacher.js没有绑定成功）
            const logoutBtn = document.getElementById('logoutBtn');
            if (logoutBtn && !logoutBtn.hasAttribute('data-bound')) {
                logoutBtn.setAttribute('data-bound', 'true');
                logoutBtn.addEventListener('click', function(e) {
                    console.log('退出登录按钮被点击（来自password页面）');
                    e.preventDefault();
                    if (typeof logout === 'function') {
                        logout();
                    } else {
                        console.error('logout函数未定义');
                    }
                });
            }
            
            // 菜单跳转逻辑
            const menu = document.getElementById('menu');
            if (menu) {
                console.log('菜单元素找到，绑定点击事件');
                menu.addEventListener('click', function(e){
                    console.log('菜单被点击');
                    const btn = e.target.closest('.menu-item');
                    if(!btn) {
                        console.log('没有找到菜单项');
                        return;
                    }
                    const view = btn.getAttribute('data-view');
                    console.log('点击的菜单项:', view);
                    
                    // 根据不同的视图进行页面跳转
                    switch (view) {
                        case 'profile':
                            console.log('跳转到首页');
                            window.location.href = '/index.html'; // 返回首页
                            break;
                        case 'schedule':
                            console.log('跳转到教师课表页面');
                            window.location.href = location.origin + '/teacher/schedule'; // 跳转到教师课表页面
                            break;
                        case 'password':
                            // 当前页面，不需要跳转
                            console.log('当前已在修改密码页面');
                            break;
                        case 'students':
                            console.log('跳转到学生信息页面');
                            window.location.href = location.origin + '/teacher/students'; // 跳转到学生信息页面
                            break;
                        case 'upload':
                            console.log('跳转到上传资料页面');
                            window.location.href = location.origin + '/teacher/postmaterial';
                            break;
                                                 case 'download':
                             console.log('跳转到下载资料页面');
                             window.location.href = location.origin + '/teacher/downloadmaterial';
                             break;
                         case 'mymaterials':
                             console.log('跳转到我的资料页面');
                             window.location.href = location.origin + '/teacher/mymaterials/';
                             break;
                        
                        
                         default:
                             console.log('未知菜单项:', view);
                             break;
                    }
                });
            } else {
                console.error('菜单元素未找到！');
            }
        });
    </script>
</body>
</html>

